<template>
  <div>
    <form @submit="handleSubmit" autocomplete="off">
      <textarea
        :rows="rows"
        class="target-1"
        :class="styleList"
        placeholder="输入.."
        v-model="currentCommand"
        @keypress="handleEnter"
      ></textarea>
    </form>

    <CommandLine
      v-for="(c, i) in commands"
      :key="c.uuid"
      :content="c"
      :number="i"
      :handleRemove="handleRemove"
      :handleModify="handleModify"
      :class="styleList"
    />
  </div>
</template>

<script>
import CommandLine from '@/components/CommandLine.vue'
import { store } from '@/store.js'
export default {
  components: {
    CommandLine
  },
  data () {
    return {
      currentCommand: '',
      commands: [],
      rows: 1

    }
  },
  methods: {
    handleSubmit (e) {
      if (!/^\s*$/.test(this.currentCommand)) {
        store.append({ uuid: this.uuidv4(), data: this.currentCommand + '' })
        this.currentCommand = ''
        this.refresh()
      }

      e.preventDefault()
    },
    refresh () {
      this.commands = [...store.state]

      this.commands.reverse()
    },
    uuidv4 () {
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (
        c
      ) {
        var r = (Math.random() * 16) | 0
        var v = c === 'x' ? r : (r & 0x3) | 0x8
        return v.toString(16)
      })
    },
    handleRemove (uuid) {
      store.removeById(uuid)
      this.refresh.bind(this)()
    },
    handleModify (uuid) {
      // this.rows = 10
      const o = store.findById(uuid)
      console.log((o.data.match(/\\/g) || []).length) // logs 3
      this.currentCommand = o.data
      this.rows = (o.data.match(/\\/g) || []).length + 2
    },
    handleEnter (e) {
      if (e.code === 'Enter' && e.shiftKey === true) {
        console.log('reached')
        this.handleSubmit(e)
        this.rows = 1
      } else if (e.code === 'Enter' && this.rows < 10) {
        this.rows += 1
        console.log(e)
      }
    }
  },
  created () {
    this.refresh()
    // this.commands.reverse()
  },
  computed: {
    theme () {
      return this.$store.state.theme
    },
    isLight () {
      return this.theme === 'light'
    },
    isDark () {
      return this.theme === 'dark'
    },
    styleList () {
      return {
        'light-bg-ft': this.isLight, 'dark-bg-ft': this.isDark
      }
    },
    hoverList () {
      return {
        'light-bg-ft': this.isLight,
        'dark-bg-ft': this.isDark,
        'light-a': this.isLight,
        'dark-a': this.isDark
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/theme";
form {
  padding-top: 20px;
}

.target-1 {
  font-size: 24px;
  height: auto;
  padding: 5px 18px;
  width: 960px;
  border-top: 0;
  border-left: 0;
  border-right: 0;
  outline: none;
  // resize: vertical;
  resize: none;
}
.editable {
  width: 960px;
  padding: 10px;
  margin-top: 10px;
  outline: none;
  /* border: #777 solid 1px; */
}
</style>
